<?php

namespace app\index\controller;

use think\Db;
use think\Exception;

class Index
{
    private $_redis = null;
    private $_alidayu = null;

    public function __construct()
    {
        if ($this->_redis === null) $this->_redis = new \MyRedis();
        if ($this->_alidayu === null) $this->_alidayu = new \Alidayu();
    }

    /*
     * 定时任务队列
     * 8 0 * * * /usr/bin/php /home/wwwroot/homegarden/index.php Timer/Temp/reverse_sync_product
     * 10 0 * * * /usr/bin/php /home/wwwroot/api/public/index.php oa/Timing/run
     * * * * * * /usr/bin/php /home/wwwroot/api/public/index.php cms/Product/run
     * 9 0 * * * /usr/bin/php /home/wwwroot/api/public/index.php cms/Present/run
     * */
    public function index()
    {
        passthru('crontab -l');
    }

    /*
     * 发送取货信息
     * */
    public function sendPickUpMessage()
    {
        for ($i = 0; $i < 10; $i++) {
            $res = $this->sendMessage();
            if ($res != 'SUCCESS') break;
        }
    }

    public function sendMessage()
    {
        $msg = $this->_redis->getHandel()->lpop('msg');
        if ($msg) {
            $message = unserialize($msg);
            try {
                $resp = $this->_alidayu->pickup($message);
                $resp = json_decode(json_encode($resp), true);
                $message['code'] = isset($resp['result']) ? 0 : $resp['sub_code'];
                $message['msg'] = isset($resp['result']) ? '' : $resp['sub_msg'];
                $message['sendtime'] = date('Y-m-d H:i:s');
                Db::table('homegarden_oa.message')->insert($message);
            } catch (Exception $e) {
                return 'ERROR:' . $e->getMessage();
            }
            return 'SUCCESS';
        }
        return 'EMPTY';
    }

    /*
     * 抽取订单信息
     * */
    public function extractOrderInfo()
    {
        $time = time();
        $date = Date('Y-m-d', $time);
        $hour = Date('H', $time);
        if ($hour == '23') {
            $date = Date('Y-m-d', strtotime("$date +1 day"));
        }

        Db::startTrans();
        try {
            // 插入订单
            DB::execute(insertInfoSql($date, 2));
            DB::execute(insertDetailSql($date, 2));
            // 订单分品
            DB::execute(insertSiteProductSql($date));
            // 订单分包
            DB::execute(insertProductSql($date));
            // 更新采购需求
            DB::execute(insertPurchaseRequireSql($date));
            // 生成采购订单
            DB::execute(insertPurchaseSql($date));
            // 匹配服务人员
            DB::execute(updateWorkerWSql($date));
            DB::execute(updateWorkerXSql($date));
            DB::execute(updateWorkerYSql($date));
            DB::execute(updateWorkerZSql($date));
            DB::commit();
            return 'SUCCESS';
        } catch (Exception $e) {
            DB::rollback();
            return 'ERROR' . $e->getMessage();
        }
        return 'EMPTY';
    }

    /*
     * 同步商品信息
     * */
    public function syncProductInfo()
    {
        $date = Date('Y-m-d H:i:s', time());

        // 先执行下线操作
        $off_list = Db::table('homegarden_timer.product')->where('off_time', 'ELT', $date)
            ->where('off_status', 0)->column('id');

        // 后执行上线操作
        $on_list = DB::table('homegarden_timer.product')->where('on_time', 'ELT', $date)
            ->where('on_status', 0)->where('off_status', 0)->column('id');

        Db::startTrans();
        try {
            if ($off_list) {
                // 更新homegarden.timer.product
                DB::table('homegarden_timer.product')->where('id', 'IN', $off_list)
                    ->update(['off_time' => date('Y-m-d H:i:s'), 'off_status' => '1']);
                // 更新homegarden_cms.product
                DB::table('homegarden_cms.product')->where('id', 'IN', $off_list)->setField('is_used', 2);
                // 更新homegarden.product
                DB::table('homegarden.product')->where('id', 'IN', $off_list)->setField('issale', 0);
                // 清空购物车
                $product_id = DB::table('homegarden_cms.product')->where('id', 'IN', $off_list)->column('code');
                DB::table('homegarden.shoppingcart')->where('product_id', 'IN', $product_id)->delete();
            }

            if ($on_list) {
                // 更新homegarden.timer.product
                DB::table('homegarden_timer.product')->where('id', 'IN', $on_list)
                    ->update(['on_time' => date('Y-m-d H:i:s'), 'on_status' => '1']);
                // 更新homegarden_cms.product
                DB::table('homegarden_cms.product')->where('id', 'IN', $on_list)
                    ->setField('is_used', 1);
                // 更新homegarden.product
                $sql = replaceProductByIds($on_list);
                DB::execute($sql);
            }

            DB::commit();
            return 'SUCCESS';
        } catch (Exception $e) {
            DB::rollback();
            return 'ERROR' . $e->getMessage();
        }
        return 'EMPTY';
    }

    /*
     * 同步赠品信息
     * */
    public function syncPresentInfo()
    {
        $present = DB::table('homegarden.present')->alias('activity')
            ->join('homegarden_cms.product pro', 'pro.activity_id = activity.active_id')
            ->join('homegarden_cms.product pre', 'pre.`code` = activity.product_id', 'LEFT')
            ->join('homegarden.product product', 'product.product_id = activity.product_id', 'LEFT')
            ->where('pro.is_used', 1)
            ->where('pre.id', 'EXP', 'IS NULL')
            ->field('
                product.id,
                product.product_id `code`,
                product.product_name `name`,
                product.product_briefDescription brief_description,
                product.product_number number,
                product.product_unit unit,
                product.product_class1 category_class1,
                product.product_class2 category_class2,
                product.product_class3 category_class3,
                product.product_headImage thumb_image,
                product.real_weight,
                1 is_gift
            ')->select();

        if ($present) {
            DB::startTrans();
            try {
                DB::table('homegarden_cms.product')->insertAll($present);
                DB::commit();
                return 'SUCCESS';
            } catch (Exception $e) {
                DB::rollback();
                return 'ERROR' . $e->getMessage();
            }
        }
        return 'EMPTY';
    }
}
